﻿using System;
using System.Data.Linq.SqlClient;
using System.Linq;
using PersonaLibrary.Data;

namespace PersonaLibrary.Search
{
	internal class AlphabetFilter : Filter
	{
		private CustomProperties.PropertiesItem _alphabet;
		private readonly bool _isSubFilter;

		public AlphabetFilter(Type filterType, bool isSubFilter)
			: this(filterType, isSubFilter, filterType.Name)
		{
		}

		public AlphabetFilter(Type filterType, bool isSubFilter, string displayName)
			: base(null, filterType)
		{
			DisplayName = displayName;
			_isSubFilter = isSubFilter;
			RefreshFilter();
			Alphabet.NeedRefresh += RefreshFilter;
		}

		private void RefreshFilter()
		{
			string name;
			if (string.IsNullOrEmpty(DisplayName))
				name = FilterType.Name;
			else
				name = DisplayName;

			if(_alphabet == null && _isSubFilter)
				_alphabet = Properties.Settings.Default.SpecializeProperties[name + "SubFilter"];

			if(_alphabet == null)
				_alphabet = Properties.Settings.Default.SpecializeProperties[name];

			if (_alphabet.IsAlphabetFilter)
			{
				Delegate expression = AlphabetExpression.CreateExpression(_alphabet, FilterType).Compile();
				
				FuncFilter = delegate(BaseEntity arg)
				{
					return (bool)expression.DynamicInvoke(arg);
				};
			}
			else
				FuncFilter = delegate(Data.BaseEntity arg)
				{ return true; };
		}

		public CustomProperties.PropertiesItem Alphabet
		{
			get { return _alphabet; }
		}
	}
}
